package com.biqee.action.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.biqee.action.base.BaseAction;
import com.biqee.framework.cookie.CookieConstants;
import com.biqee.framework.cookie.CookieManager;
import com.biqee.model.db.BqUserTb;
import com.biqee.service.db.BqUserTbService;
import com.biqee.service.user.LoginService;
import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionContext;

/**
 * 处理来自淘宝信任登录的Action
 * 
 * @author guotao.tangt
 *
 */
public class TbTrustLoginAction extends BaseAction {

	private static final long serialVersionUID = -294421989060439475L;
	
	public String login() {
		if(nick == null || sessionKey == null) {
			return "index";
		}
		
		// TODO 查询订购记录，创建用户
		
		// 执行登录
		BqUserTb bqUserTb = bqUserTbService.readById(0L);
		Long bqUserId = bqUserTb.getBqUserId();
		loginService.login(bqUserId);
		
		writeCookie(bqUserId);
		
		// TODO modify me
		return null;
	}

	private void writeCookie(Long bqUserId) {
		ActionContext ctx = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
		CookieManager cookieManager = new CookieManager(request);
		
		cookieManager.setValue(CookieConstants.NAME_BQ,
				CookieConstants.KEY_USER_ID, bqUserId.toString());
		HttpServletResponse reponse = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);
		cookieManager.save(reponse, CookieConstants.NAME_BQ,
				CookieConstants.DOMAIN, CookieConstants.PATH, CookieConstants.MAX_COOKIE_AGE);
	}
	
	/*  ------------- bean injected by Spring -------- */
	private BqUserTbService bqUserTbService;
	
	public void setBqUserTbService(BqUserTbService bqUserTbService) {
		this.bqUserTbService = bqUserTbService;
	}

	private LoginService loginService;
	
	public void setLoginService(LoginService loginService) {
		this.loginService = loginService;
	}

	/*  ------------- Model Driven ------------------- */
	private String nick;
	
	public String getNick() {
		return nick;
	}

	public void setNick(String nick) {
		this.nick = nick;
	}
	
	private String sessionKey;

	public String getSessionKey() {
		return sessionKey;
	}

	public void setSessionKey(String sessionKey) {
		this.sessionKey = sessionKey;
	}
	
	
}
